<template>
	<view>
		<view class="nav-type">
			<uni-segmented-control :current="current" :values="[$t('webAuto.ProcessForm'), $t('webAuto.ProcessSteps')]" @clickItem="switchItem"
				styleType="text" activeColor="#4C87F3"></uni-segmented-control>
		</view>
		<scroll-view class="w-submit-form" scroll-y show-scrollbar :style="{height: content.height + 'px'}"
			@scroll="scroll" style="margin-bottom: 120rpx;">
			<view v-show="current === 0">
				<view class="w-start-dept" v-if="userDepts.length > 1">
					<view>{{$t('webAuto.InitiatorDepartment')}}</view>
					<uni-data-checkbox v-model="startDept" :localdata="userDepts"></uni-data-checkbox>
				</view>
				<form-render ref="wform" :config="model.formConfig" :jsonConf="model.formItems" v-model="formData"></form-render>
			</view>
			<view class="w-process-render" v-show="current === 1">
				<process-render @render-ok="submitLoading = false" ref="process" v-if="!loading && startDept"
					:process-def-id="model.processDefId" :dept-id="startDept" v-model="processUsers"
					:formData="formData" :process="model.process" />
			</view>
			<!-- <view v-if="content.isIos" class="w-submit-opration">
				<button class="w-button" type="primary" @click="submitProcess">提交流程</button>
			</view> -->
		</scroll-view>
		<view class="w-submit-opration" >
			<button class="w-button" type="primary" @click="submitProcess">{{$t('webAuto.SubmissionProcess')}}</button>
			<button class="w-button" type="primary" style="width:25%;background-color:#E6A23C ;"  @click="submitDraft">{{$t('webAuto.ProcessDraft')}}</button>
		</view>

	</view>

</template>

<script setup>
	import FormRender from '@/components/FormRender.vue'
	import ProcessRender from './ProcessRender.vue'
	import { ref, computed } from "vue";
	import { debounce } from '@/utils/tool.js'
	import { onLoad, onBackPress } from "@dcloudio/uni-app";
	import { getUserDepts } from '@/api/org.js'
	import { getInstanceFormData } from '@/api/task.js'
	import { getModelById } from '@/api/model.js'
	import { startProcess, getStaging } from '@/api/process.js'
	import { useI18n } from 'vue-i18n';


	const { t } = useI18n()

	const wform = ref()
	const process = ref()
	//表单数据
	const formData = ref({})
	//流程表单设计数据
	const model = ref({})
	const userDepts = ref([])
	//发起流程的部门
	const startDept = ref(null)
	//流程节点自选审批人/抄送人
	const processUsers = ref({})
	const submitLoading = ref(false)
	const loading = ref(false)
	//tab选项卡
	const current = ref(0)

	const content = computed(() => {
		const sys = uni.getSystemInfoSync()
		const isIos = sys.platform === 'ios'
		const h = sys.windowHeight
		return {
			isIos: isIos,
			height: isIos ? h - 36 : h - 70 - 36
		}
	})

	onLoad((v) => {
		getModelInfo(v.code || '')
		getUserDept()
		// 存稿打开的进行赋值
		if(v.formDatas){
			let formDatas = JSON.parse(v.formDatas)
			if(Object.keys(formDatas).length>0){
				Object.keys(formDatas).forEach(name=>{
					formData.value[name]=formDatas[name]
				})
			}
		}
	})

	//当前登录的用户
	const loginUser = uni.getStorageSync('loginUser')

	//滚动延时去抖动
	const scDebounce = debounce(() => uni.$emit('showFp'), 500)

	function getModelInfo(code) {
		loading.value = true
		getModelById(code).then(rsp => {
			model.value = rsp.data;
			loading.value = false
			//构建表单及校验规则
			//this.loadFormData()
		})
	}

	function getUserDept() {
		getUserDepts(loginUser.userId).then(rsp => {
			userDepts.value = (rsp.data || []).map(v => {
				return {text: v.name, value: v.id}
			});

			if (userDepts.value.length > 0) {
				startDept.value = userDepts.value[0].value
			}
		})
	}

	function switchItem(v) {
		current.value = v.currentIndex;
		uni.$emit(current.value === 0 ? 'showFp' : 'hideFp')
	}

	function scroll(v) {
		// #ifdef APP-VUE
		uni.$emit('wv:scorll')
		//刷新文件选择器定位
		//#endif
		scDebounce()
	}

	function submitProcess() {
		wform.value.validate(formValid => {
			if (formValid) {
				process.value.validate(processValid => {
					if (processValid) {
						doSubmit()
					} else {
						current.value = 1
						uni.showToast({
							icon: 'none',
							title: t('webAuto.FollowProcessOptions')
						})
					}
				})
			} else {
				current.value = 0
				uni.showToast({
					icon: 'none',
					title: t('webAuto.FollowFormOptions')
				})
			}
		})
	}

	// 流程存稿
	function submitDraft() {
		// console.log(startDept.value)
		getStaging({
		formId: model.value.formId,
          param: formData.value
        }).then(res => {
          // console.log(res)
		  uni.showToast({
				icon: 'none',
				title: t('webAuto.ProcessDraft') + res.data
			})
        })
	}

	function doSubmit() {
		let startParams = {
			deptId: startDept.value,
			formData: formData.value,
			processUsers: processUsers.value
		}
		startProcess(model.value.processDefId, startParams).then(rsp => {
			uni.showToast({
				icon: 'success',
				title: t('webAuto.SuccessfullyInitiated')
			})
			uni.switchTab({
				url: '/pages/submit/submit'
			})
		}).catch(err => {
			uni.showToast({
				icon: 'none',
				title: t('webAuto.InitiateFailed') + err.msg
			})
		})
	}
</script>

<style lang="less" scoped>
	.w-start-dept {
		background: white;
		padding: 20rpx;
		margin-bottom: 20rpx;
		&>view {
			margin-bottom: 5rpx;
		}
	}
	.w-submit-opration {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		.w-button{
			height: 100rpx !important;
			line-height: 100rpx !important;
		}
		//background-color: white;
		&>button {
			width: 75%;
			// margin: 0 32rpx;
			border-radius: 8rpx !important;
		}
	}

	.w-process-render {
		background-color: white;
		padding: 16rpx;
	}

	.nav-type {
		background-color: rgb(255, 255, 255);
		border-bottom: 1px solid #F4F5F7;
	}
</style>
